package kplayer

import (
	"bufio"
	"io"
	"os/exec"
	"strings"
)

type KPlayer struct {
}

func (KPlayer)Run() {
	_, err := runCommand("/home/alomerry-home/apps/home/backend/lib/kplayer/kplayer", "play", "start", "--daemon")
	if err != nil {
		panic(err)
	}
}

func Stop() {
	_, err := runCommand("/home/alomerry-home/apps/home/backend/lib/kplayer/kplayer", "play", "start", "--daemon")
	if err != nil {
		panic(err)
	}
}

func runCommand(name string, arg ...string) (string, error) {
	var (
		cmd    = exec.Command(name, arg...)
		result = &strings.Builder{}
		err    error
	)

	out, err := cmd.StdoutPipe()
	if err != nil {
		return "", err
	}
	defer out.Close()

	cmd.Stderr = cmd.Stdout // 命令的错误输出和标准输出都连接到同一个管道

	if err = cmd.Start(); err != nil {
		return "", err
	}

	read := bufio.NewReader(out)
	for {
		line, _, err := read.ReadLine()
		if err == io.EOF {
			break
		}
		result.WriteString(string(line))
		result.WriteString("\n")
	}
	cmd.Wait()
	return result.String(), nil
}
